package org.dromara.common.wukong.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import lombok.RequiredArgsConstructor;
import okhttp3.Response;
import org.dromara.common.model.OkHttpUtils;
import org.dromara.common.wukong.constant.WuKongConversationConstant;
import org.dromara.common.wukong.properties.WuKongImProperties;
import org.dromara.common.wukong.service.WuKongConversationService;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

/**
 * @Author: Stars
 * @Date: 2025/5/18 21:04
 */
@Service
@RequiredArgsConstructor
public class WuKongConversationServiceImpl implements WuKongConversationService {

    private final WuKongImProperties wuKongImProperties;

    @Override
    public JSONArray syncConversation(Long userId) throws IOException {
        Response response = OkHttpUtils.post(wuKongImProperties.getUrl() + WuKongConversationConstant.CONVERSATION_SYNC, Map.<String, Object>of("uid", userId.toString(), "version", 0, "last_msg_seqs", "", "msg_count", 1));
        if (response.code() != 200) {
            throw new IOException("获取同步最近会话" + response.body().string());
        }
        if (response.code() == 200) {
            String body = response.body().string();
            JSONArray messagesArray = JSON.parseArray(body);
            return messagesArray;
        }
        throw new IOException("获取同步最近会话失败" + response.body().string());
    }

    @Override
    public void setConversationUnreadCount(Long userId, String channelId, Integer channelType) throws IOException {
        Response response = OkHttpUtils.post(wuKongImProperties.getUrl() + WuKongConversationConstant.CONVERSATIONS_SET_UNREAD, Map.<String, Object>of("uid", userId.toString(), "channel_id", channelId, "channel_type", channelType));
        if (response.code() != 200) {
            throw new IOException("获取同步最近会话" + response.body().string());
        }
        if (response.code() == 200) {
            return;
        }
        throw new IOException("设置同步最近会话未读数量" + response.body().string());
    }

    @Override
    public void deleteConversation(Long userId, String channelId, Integer channelType) throws IOException {
        Response response = OkHttpUtils.post(wuKongImProperties.getUrl() + WuKongConversationConstant.CONVERSATIONS_DELETE, Map.<String, Object>of("uid", userId.toString(), "channel_id", channelId, "channel_type", channelType));
        if (response.code() != 200) {
            throw new IOException("删除会话列表异常" + response.body().string());
        }
        if (response.code() == 200) {
            return;
        }
        throw new IOException("删除会话列表异常" + response.body().string());
    }
}
